<?php

declare(strict_types=1);

namespace app\model\esxsys;

use think\Model;
use think\facade\Db;
use think\facade\Cache;
use app\eslib\EsUtils;
use app\model\ModelUtils;

/**
 * 用户反馈模型类
 * @version 1.0.0
 */
class FeedbacksModel extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'esxsys_feedbacks';

    // 开启自动时间戳（默认为整型int）
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    /**
     * 返回 是否已阅 访问器的数据
     * @return array
     */
    public function getIsReadDataAttr(): array
    {
        return [
            ['text' => '否', 'value' => 0],
            ['text' => '是', 'value' => 1],
        ];
    }

    /**
     * 返回 是否已阅 访问器的值
     * @return string
     */
    public function getIsReadTextAttr($value, $data)
    {
        $value = $data['is_read'];
        if (is_numeric($value)) {
            $value = intval($value);
        }
        $data = (array) $this->getIsReadDataAttr();
        $result = array_filter($data, function ($v) use ($value) {
            return $v['value'] == $value;
        }, ARRAY_FILTER_USE_BOTH);
        return $result ? current($result)['text'] : $value;
    }
    /**
     * 返回 是否匿名 访问器的数据
     * @return array
     */
    public function getIsAnonymousDataAttr(): array
    {
        return [
            ['text' => '否', 'value' => 0],
            ['text' => '是', 'value' => 1],
        ];
    }

    /**
     * 返回 是否匿名 访问器的值
     * @return string
     */
    public function getIsAnonymousTextAttr($value, $data)
    {
        $value = $data['is_anonymous'];
        if (is_numeric($value)) {
            $value = intval($value);
        }
        $data = (array) $this->getIsAnonymousDataAttr();
        $result = array_filter($data, function ($v) use ($value) {
            return $v['value'] == $value;
        }, ARRAY_FILTER_USE_BOTH);
        return $result ? current($result)['text'] : $value;
    }
    /**
     * 返回 状态 访问器的数据
     * @return array
     */
    public function getStatusDataAttr(): array
    {
        return [
            ['text' => '隐藏', 'value' => 0],
            ['text' => '正常', 'value' => 1],
        ];
    }

    /**
     * 返回 状态 访问器的值
     * @return string
     */
    public function getStatusTextAttr($value, $data)
    {
        $value = $data['status'];
        if (is_numeric($value)) {
            $value = intval($value);
        }
        $data = (array) $this->getStatusDataAttr();
        $result = array_filter($data, function ($v) use ($value) {
            return $v['value'] == $value;
        }, ARRAY_FILTER_USE_BOTH);
        return $result ? current($result)['text'] : $value;
    }

    /**
     * 获取指定层级的父级ID（递归）
     */
    public static function getPid($id, $deepth = 0, $_level = 0)
    {
        $table = (new static())->table;
        $cacheKey = "{$table}_pid_{$id}_{$deepth}";
        if ($_level == 0) {
            $data = Cache::get($cacheKey);
            if ($data) {
                return $data;
            }
        }
        $pid = Db::table($table)->where('id', $id)->value('pid');
        if ($pid == 0 || $_level == $deepth) {
            $data = $pid;
        } else {
            $data = self::getPid($pid, $deepth, $_level + 1);
        }
        if ($_level == 0) {
            Cache::set($cacheKey, $pid);
            ModelUtils::cachePut($table, $cacheKey);
        }
        return $data;
    }

    /**
     * [弃用] 返回多维树形数据（通用数据，使用 _children 包含子项目）
     */
    public static function getTreeData($pid = 0, $_level = 0)
    {
        $table = (new static())->table;
        $cacheKey = "{$table}_tree_data_{$pid}";
        if ($_level == 0) {
            $data = Cache::get($cacheKey);
            if ($data) {
                return $data;
            }
        }
        $list = self::where('pid', $pid)->append(['is_read_text', 'is_anonymous_text', 'status_text'])->select()->toArray();

        $data = [];
        foreach ($list as $row) {
            $row['_children'] = self::getTreeList($row['id'], $_level + 1);
            $data[] = $row;
        }
        unset($list);
        if ($_level == 0) {
            Cache::set($cacheKey, $data);
            ModelUtils::cachePut($table, $cacheKey);
        }
        return $data;
    }
    /**
     * 返回一维树形列表数据（名称带层级符号，用于管理表格）
     */
    public static function getTreeRows($pid = 0, $_level = 0)
    {
        $table = (new static())->table;
        $cacheKey = "{$table}_tree_rows_{$pid}";
        if ($_level == 0) {
            $data = Cache::get($cacheKey);
            if ($data) {
                return $data;
            }
        }
        $list = self::where('pid', $pid)->order('id')->select();
        $data = [];
        foreach ($list as $row) {
            $row->_prefix = str_repeat('|----', $_level);
            $row->_level = $_level;
            $data[] = $row;
            $listTemp = self::getTreeRows($row['id'], $_level + 1);
            if ($listTemp) {
                $data = array_merge($data, $listTemp);
            }
        }
        unset($list);
        if ($_level == 0) {
            Cache::set($cacheKey, $data);
            ModelUtils::cachePut($table, $cacheKey);
        }
        return $data;
    }
    /**
     * 返回一维树形字典数据（名称带层级符号，用于表单下拉框。KV结构：{text:...,value:...,_level:...,_prefix:...}）
     */
    public static function getDictData($pid = 0, $_level = 0)
    {
        $table = (new static())->table;
        $cacheKey = "{$table}_dict_data_{$pid}";
        if ($_level == 0) {
            $data = Cache::get($cacheKey);
            if ($data) {
                return $data;
            }
        }
        $list = Db::table($table)->where('pid', $pid)->order('id')->select()->toArray();
        $data = [];
        $rowTemp = [];
        foreach ($list as $row) {
            $rowTemp = ['text' => str_repeat('|----', $_level) . $row['xxx_name'], 'value' => $row['id'], '_level' => $_level];
            $data[] = $rowTemp;
            $listTemp = self::getDictData($row['id'], $_level + 1);
            if ($listTemp) {
                $data = array_merge($data, $listTemp);
            }
        }
        unset($list);
        if ($_level == 0) {
            array_unshift($data, ['text' => '请选择分类', 'value' => 0, '_level' => $_level]);
            Cache::set($cacheKey, $data);
            ModelUtils::cachePut($table, $cacheKey);
        }
        return $data;
    }

    /**
     * 获取资源分页列表（支持分页和搜索，用于管理表格）
     */
    public static function getListData($page, $pageSize, $searchText)
    {
        $table = (new static())->table;
        $cacheKey = EsUtils::shortMD5("{$table}_{$page}_{$pageSize}_{$searchText}");
        $data = Cache::get($cacheKey);
        if ($data) {
            return $data;
        }
        if ($searchText) {
            $data = self::where('id', intval($searchText))->whereOr('xxx_name', 'like', "%{$searchText}%")->paginate($pageSize);
            if ($data) {
                $data->append(['is_read_text', 'is_anonymous_text', 'status_text']);
            }
        } else {
            $data = self::getTreeRows();
            $data = ['total' => count($data), 'data' => EsUtils::arrayPaginate($data, $page, $pageSize)];
        }
        Cache::set($cacheKey, $data);
        ModelUtils::cachePut($table, $cacheKey);
        return $data;
    }

    public static function getUsers($pageSize = 10)
    {
        $list = Db::table('esxsys_feedback')->field('user_id')->group('user_id')->paginate($pageSize)->toArray();
        if (!$list) {
            return [];
        }
        $userIds = [];
        $list = $list['data'];
        foreach ($list as $row) {
            $userIds[] = $row['user_id'];
        }
        return Db::table('usr_user')->where('id', 'in', $userIds)->field('id, user_name')->select();
    }
}
